<?php

namespace app\index\service;

use app\common\model\AccountBill;
use app\common\model\Margin;
use app\common\service\MarginService;
use app\index\dao\MarginDao;
use app\index\model\UM as UM;
use ShidianUtil\Exception\DataNotExistException;
use think\Collection;
use think\exception\ValidateException;

/**
 * Class MarginConfirmService
 * @package app\index\service
 */
class MarginConfirmService
{
    // dao
    private MarginDao $marginDao;

    public function __construct(MarginDao $marginDao)
    {
        $this->marginDao = $marginDao;
    }

    /**
     *
     * @param UM|null $user
     * @param int|null $page
     * @param int|null $page_size
     * @return Collection
     */
    public function index(?UM $user, $memberId, ?int $page = null, ?int $page_size = null): Collection
    {
        if ($user) {
            $memberId = $user->id;
        }

        if (!is_id($memberId)) {
            return \think\model\Collection::make();
        }

        //这里如果要修改查询，建议把查询放到dao层去
        return $this->marginDao->selectByMemberId($memberId, $page, $page_size);
    }

    /**
     * 更新
     * @param UM|null $user
     * @param int $id
     * @param array $params
     * @return void
     */
    public function modify(?UM $user, int $id, array $params): void
    {
        $memberId = $user ? $user->id : 0;
        $confirmStatus = $params['confirmStatus'] ?? 1;
        $confirmStatus = $confirmStatus == 1 ? 1 : 2;

        //这里如果要修改查询，建议把查询就放到这里
        $record = Margin::field(true)->where('id', $id)->find();

        if (is_null($record)) {
            throw new DataNotExistException('该信息不存在或已被删除');
        }

        if ($record->confirmStatus != 0) {
            throw new ValidateException('请勿重复操作');
        }

        $this->getMarginService()->confirm($record->id, $confirmStatus, AccountBill::MEMBER, $memberId);
    }

    private function getMarginService(): MarginService
    {
        return app(MarginService::class);
    }
}
